package com.primestone.cim.executemeterreadschedules.async;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.primestone.cim.entities.tmp.ResMeterReadSchedules;

/**
 * Session Bean implementation class TmpTableEJBBean
 */
@TransactionManagement( TransactionManagementType.CONTAINER )
@Stateless(mappedName = "TmpTableEJB", name = "TmpTableEJB")
public class TmpTableEJBBean implements TmpTableEJBLocal {
	
	@PersistenceContext( unitName = "TmpTablesGMR" )
	protected EntityManager em;

    /**
     * Default constructor. 
     */
    public TmpTableEJBBean() {
        // Auto-generated constructor stub
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void saveMeterReadSchedules(ResMeterReadSchedules resMeterReadSchedule) {
		em.persist(resMeterReadSchedule);
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void saveMeterReadSchedules(List<ResMeterReadSchedules> resMeterReadSchedules) {
    	for (ResMeterReadSchedules resMeterReadSchedule : resMeterReadSchedules) {
			em.persist(resMeterReadSchedule);
		}
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public ResMeterReadSchedules findSchedulesOperationResultByTicket(String ticket) {
    	try {
            Query query = em.createNamedQuery( "ResMeterReadSchedules.findByTicket" );
            query.setParameter( "ResMeterReadSchedules_ticket", ticket );

            return ( ResMeterReadSchedules )query.getSingleResult();

        } catch( NoResultException e ) {
            return null;
        }
    }
    
    @TransactionAttribute( value = TransactionAttributeType.REQUIRES_NEW )
    public void deleteScheduleOperationResult(ResMeterReadSchedules resMeterReadSchedule) {
    	em.remove( em.merge( resMeterReadSchedule ) );
    }

}
